package com.xiaoyg.algorithm.lru;

import java.util.LinkedHashMap;

public class LRUCacheUtils {
    int cap;
    LinkedHashMap<Integer,Integer> cache = new LinkedHashMap<>();

    public  LRUCacheUtils (int cap){
        this.cap = cap;
    }

    public int get(int key){
        if (!cache.containsKey(key)){
            return -1;
        }
        makeRecently(key);
        return cache.get(key);
    }

    public void put(int key, int val){
        //如果存在就修改值，并将key塞到队尾
        if (cache.containsKey(key)){
            cache.put(key,val);
            makeRecently(key);
            return;
        }

        //容量超容，取出队头删除
        if (cache.size() > cap){
            Integer next = cache.keySet().iterator().next();
            cache.remove(next);
        }
        //将key,val塞到队尾
        cache.put(key,val);
    }

    private void makeRecently(int key) {
        Integer next = cache.get(key);
        //删除元素，塞到队尾
        cache.remove(next);
        cache.put(key,next);
    }


}
